package com.jch.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.jch.oss.service.OssService;
import com.jch.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        //获取OSS信息
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {
            //创建oss实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();

            //获取文件名称
            String filename = file.getOriginalFilename();
            //给文件名称加上随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //把文件按照日期进行分类
            String datePath = new DateTime().toString("yyyy/MM/dd");
            filename = datePath+"/"+uuid+filename;
            //调用OSS方法实现文件上传
            //第一个参数，Bucket名称
            //第二个参数，上传到oss文件路径和文件名称
            //第三个参数，上传文件输入流
            ossClient.putObject(bucketName, filename, inputStream);
            //关闭Oss
            ossClient.shutdown();
            //设置上传文件路径
            String url="http:s//"+bucketName+"."+endpoint+"/"+filename;
            return url;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
    }
}
